package br.com.werp.regras.geral.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import br.com.werp.regras.geral.Debuger;

/**
 * @author Sobreira
 * Criado em 26/05/2006
 */
public class CodeSubstTemplate {

    private static int actionCont;
    private final static String TARGET = "GerenciadorErros.logarErro(e);";
    private final static String TARGET2 = "throw new ErroPadrao;";
    private final static String TARGET3 = "throw new ErroPadrao/(GerenciadorErros.logarErro/(e/)/);";
    


    public static void main(String[] args) throws Exception {
        String appDir = "D:\\temp\\RegrasNegocio\\br"; // args[0];
        File webAppRoot = new File(appDir);
        loopFiles(webAppRoot);
        System.out.println(actionCont + " Actions formatadas.");
    }

    /**
     * @param file
     * @throws Exception
     */
    private static void loopFiles(File file) throws Exception {
        if (file.getName().endsWith("Impl.java")) {
            executaSubistituicao(file);
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (int i = 0; i < files.length; i++) {
                loopFiles(files[i]);
            }
        }
    }

    private static void executaSubistituicao(File file)
        throws Exception {

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();
        StringBuffer conteudo = new StringBuffer();

        while (line != null) {
            if (line.indexOf(TARGET) != -1) {
                System.out.println(line);
             }else   if (line.indexOf(TARGET2) != -1) {
                line= line.replaceAll(TARGET2, TARGET3);
                conteudo.append(line).append("\n");
             } else{
                conteudo.append(line).append("\n");
            }
            
            line = reader.readLine();
        }

        String canonicalPath = file.getCanonicalPath();

        Debuger.debugar(file.getCanonicalPath().toString(),
            ActionExceptionParse.class);
        actionCont++;
        file.delete();

        FileWriter fileWriter = new FileWriter(canonicalPath);
        fileWriter.write(conteudo.toString());
        fileWriter.close();
    }

}
